package main.java.indi.zyj.c150.back;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class _07_CombinationSum2 {


    List<List<Integer>> res = new ArrayList<>();

    LinkedList<Integer> path = new LinkedList<>();

    int currentSum = 0;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {

        if (candidates == null || candidates.length == 0) {
             return res;
        }

        Arrays.sort(candidates);

        backtrack(candidates, target, 0);

        return res;

    }

    private void backtrack(int[] candidates, int target, int start) {

        if (target == currentSum) {
            res.add(new ArrayList<>(path));
            return;
        }

        if (currentSum > target) {
            return;
        }

        for (int i = start; i < candidates.length; i++) {

            if (i > start && candidates[i] == candidates[i - 1]) {
                continue;
            }

            currentSum += candidates[i];
            path.addLast(candidates[i]);
            backtrack(candidates, target, i + 1);
            path.removeLast();
            currentSum -= candidates[i];
        }

    }


}
